package org.jeecg.qis.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.basic.vo.MesOptionVO;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.prod.entity.MesBomHeaderWo;
import org.jeecg.prod.entity.MesWoSrc;
import org.jeecg.prod.service.IMesWoSrcService;
import org.jeecg.qis.entity.*;
import org.jeecg.qis.mapper.QisProcrecordMapper;
import org.jeecg.qis.mapper.QisRuleCfgMapper;
import org.jeecg.qis.service.IQisProcdetailCfgService;
import org.jeecg.qis.service.IQisProcdetailValueService;
import org.jeecg.qis.service.IQisProcheadValueService;
import org.jeecg.qis.service.IQisProcrecordService;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: qis_procrecord
 * @Author: shaolong
 * @Date: 2023-05-21
 * @Version: V1.0
 */
@Service
public class QisProcrecordServiceImpl extends ServiceImpl<QisProcrecordMapper, QisProcrecord> implements IQisProcrecordService {
    @Autowired
    private CommonAPI commonAPI;
    @Autowired
    private IMesWoSrcService iMesWoSrcService;
    @Autowired
    private IQisProcheadValueService iQisProcheadValueService;
    @Autowired
    private IQisProcdetailValueService iQisProcdetailValueService;
    @Autowired
    private IQisProcdetailCfgService iQisProcdetailCfgService;
    @Autowired
    private QisRuleCfgMapper qisRuleCfgMapper;


    @Override
    public IPage<QisProcrecord> pageList(Page<QisProcrecord> page, QisProcrecord qisProcrecord) {
        return null;
    }

    @Override
    public Result<String> addRecord(QisProcrecord qisProcrecord) {
        //补全检验单内容
        //生成ID和检验单号
        Integer value = commonAPI.getCounterValue("recid.qis_procrecord","0");
		qisProcrecord.setRecId(value.toString());
		Integer checkNo = commonAPI.getCounterValue("checklist","1");
		String inspectionNumber = generateInspectionNumber(checkNo);
		qisProcrecord.setChecklistno(inspectionNumber);
        //查询该工单对应的产品号
        MesWoSrc woid = iMesWoSrcService.query().eq("woid", qisProcrecord.getWoid()).one();
        qisProcrecord.setPartno(woid.getPartno());
        qisProcrecord.setStatus("0");
        qisProcrecord.setResult("0");
        this.save(qisProcrecord);
        //生成检验单明细
        return null;
    }

    @Override
    public Result<String> createRecord(QisProcrecord qisProcrecord) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //生成工序检验单
        String checkListNo = "";
        if(Objects.isNull(qisProcrecord.getRecId())){
            Integer checklist = commonAPI.getCounterValue("checklist","1");
            String formattedNumber = String.format("%04d", checklist);
            // 获取当前日期
            Date currentDate = new Date();
            // 定义日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            // 格式化日期
            String formattedDate = dateFormat.format(currentDate);
            // 生成时间戳
            checkListNo = "QC" + formattedDate+formattedNumber;
            Integer recId = commonAPI.getCounterValue("recid.qis_procrecord","0");
            qisProcrecord.setRecId(recId.toString());
            qisProcrecord.setChecklistno(checkListNo);
            //qisProcrecord
            //List<MesWoSrc> list = iMesWoSrcService.list(new QueryWrapper<MesWoSrc>().eq("WOID", qisProcrecord.getWoid()));
            //qisProcrecord.setPartno(list.get(0).getPartno());
        }else{
            checkListNo = qisProcrecord.getChecklistno();
        }
        String op = qisProcrecord.getOp();
        if (op.contains(",")){
            List<String> list = Arrays.asList(op.split(","));
            String finalCheckListNo = checkListNo;
            for(String item:list){
                Integer value = commonAPI.getCounterValue("recid.qis_prochead_value","0");
                QisProcheadValue qisProcheadValue = new QisProcheadValue();
                qisProcheadValue.setChecklistno(finalCheckListNo);
                qisProcheadValue.setChkdate(new Date());
                qisProcheadValue.setTimes(1);
                qisProcheadValue.setRecId(value.toString());
                qisProcheadValue.setOp(item);
                qisProcheadValue.setRemark(qisProcrecord.getRemark());
                qisProcheadValue.setUser(sysUser.getUsername());
                qisProcheadValue.setResult("0");
                qisProcheadValue.setDispose("0");
                iQisProcheadValueService.save(qisProcheadValue);
                insertDetails(qisProcrecord,  value, item);
            }
        }else {
            Integer value = commonAPI.getCounterValue("recid.qis_prochead_value","0");
            QisProcheadValue qisProcheadValue = new QisProcheadValue();
            qisProcheadValue.setRecId(value.toString());
            qisProcheadValue.setChecklistno(qisProcrecord.getChecklistno());
            qisProcheadValue.setChkdate(new Date());
            qisProcheadValue.setTimes(1);
            qisProcheadValue.setOp(op);
            qisProcheadValue.setRemark(qisProcrecord.getRemark());
            qisProcheadValue.setUser(sysUser.getUsername());
            qisProcheadValue.setResult("0");
            iQisProcheadValueService.save(qisProcheadValue);
            insertDetails(qisProcrecord,  value, op);
        }
        //修改当前单据状态
        qisProcrecord.setStatus("1");
        qisProcrecord.setResult("0");
        qisProcrecord.setCtime(new Date());
        qisProcrecord.setUsername(sysUser.getUsername());
        this.saveOrUpdate(qisProcrecord);
    return Result.OK("生成成功");
    }

    private synchronized void insertDetails(QisProcrecord qisProcrecord,Integer value,String op){
        //通过主键ID生成具体项目列表与抽检数
        List<QisProcdetailCfg> qisProcdetailCfgs = iQisProcdetailCfgService.getListByParam(qisProcrecord,op);
        qisProcdetailCfgs.forEach(item2->{
            String groupid = item2.getGroupid();
            List<QisRuleCfg> ruleCfgs = qisRuleCfgMapper.selectList(new QueryWrapper<QisRuleCfg>().eq("GROUPID", groupid));
            int qty = 0;
            if (ruleCfgs.isEmpty()){
                qty = 1;
            }else{
                QisRuleCfg qisRuleCfg = ruleCfgs.get(0);
                qty = qisRuleCfg.getValue();
            }
            ArrayList<QisProcdetailValue> list = new ArrayList<>();
            for (int i = 1; i <= qty; i++){
                QisProcdetailValue qisProcdetailValue = new QisProcdetailValue();
                Integer recId = commonAPI.getCounterValue("recid.qis_procdetail_value","0");
                qisProcdetailValue.setRecId(recId.toString());
                qisProcdetailValue.setHeadid(value.toString());
                qisProcdetailValue.setDataid(String.valueOf(item2.getRecId()));
                qisProcdetailValue.setValue("");
                qisProcdetailValue.setLowLimit(item2.getLowLimit());
                qisProcdetailValue.setUpLimit(item2.getUpLimit());
                qisProcdetailValue.setResult("0");
                qisProcdetailValue.setUnitsn(String.valueOf(i));
                list.add(qisProcdetailValue);
                iQisProcdetailValueService.save(qisProcdetailValue);
            }

        });
    }

    @Override
    public Result<List<MesOptionVO>> queryOPListByWoid(String woid,String type) {
        List<MesOptionVO> list = baseMapper.queryOPListByWoid(woid,type);
        return Result.OK(list);
    }

    @Override
    public Result<List<MesBomHeaderWo>> getWoOption() {
        List<MesBomHeaderWo> list =baseMapper.getWoOption();
        return Result.OK(list);
    }

    @Override
    public void delMain(String checkNo) {
        //1删除该单据所有明细数据
        baseMapper.delDeatails(checkNo);
        //2删除该单据所有工序数据行
        baseMapper.deleteHeads(checkNo);
        //3删除单据
        Map<String, Object> map = new HashMap<>();
        map.put("CHECKLISTNO", checkNo);
        baseMapper.deleteByMap(map);
    }

    @Override
    public void updateRecordStatus(String headId) {
        QisProcrecord qisProcrecord =this.baseMapper.updateRecord(headId);
        if(qisProcrecord!=null){
            //修改状态
            LambdaUpdateWrapper<QisProcrecord> updateWrapper = new LambdaUpdateWrapper<QisProcrecord>()
                    .set(QisProcrecord::getStatus, qisProcrecord.getStatus())
                    .set(QisProcrecord::getResult, qisProcrecord.getResult())
                    .eq(QisProcrecord::getChecklistno, qisProcrecord.getChecklistno());
            this.update(updateWrapper);
        }
    }

    public static String generateInspectionNumber(Integer sequenceNumber) {
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String datePart = dateFormat.format(new Date());
        // 格式化序号为四位数，不足四位时前面填充0
        String sequencePart = String.format("%04d", sequenceNumber);
        // 组合生成检验单号
        return "QC" + datePart + sequencePart;
    }
}
